package cn.shentianlan.interceptor;

import cn.shentianlan.controller.UserController;
import cn.shentianlan.domain.User;
import cn.shentianlan.service.UserService;
import cn.shentianlan.utils.CookieUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class AutoLoginInterceptor implements HandlerInterceptor {

    @Resource
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie cookie = CookieUtils.getCookie(request, "autoLoginCookie");
        if (cookie != null && cookie.getValue().length() > 0) {
            String[] cookieValues = cookie.getValue().split("###");
            User user = userService.findUser(cookieValues[0], cookieValues[1]);
            if (user != null) {
                HttpSession session = request.getSession();
                session.setAttribute("loginUser", user);
                request.getRequestDispatcher("/WEB-INF/pages/monitoring.jsp").forward(request, response);
                return false;
            }
        }
        return true;
    }
}
